import re
import time
from jenkins_python_api import jenkins_api_plugin
from jenkinslib import jenkins_api


if __name__ == '__main__':
    # 00.设置访问的用户
    jenkins_url = "http://192.168.1.250:8080/jenkins/"
    username = "admin"
    password = "123456"

    # 01.使用官方模块 - 获取正在运行的任务信息
    jenkins_server = jenkins_api_plugin(jenkins_url, username=username, password=password)

    job_data = None
    while True:
        try:
            job_data = jenkins_server.get_executor_jobs()
            print(job_data)
            if job_data:
                break
        except Exception as e:
            print(e)

    # 02.调用原生接口 - 获取对应任务的构建信息
    jenkins_lib_server = jenkins_api(jenkins_url, username=username, password=password)

    # 03.计算当前正在构建的任务构建时长
    send_data = []
    for job in job_data:
        url = job['url'].replace('/' + str(job['number'] + '/'), '')
        number = job['number']

        # print(url)
        builds_data = jenkins_lib_server.get_job_builds_by_url(url)

        for build_data in builds_data:
            if build_data['number'] == number:
                # 当前时间戳
                now_timestamp = int(round(time.time() * 1000))
                # 开始构建时间
                build_timestamp = build_data['timestamp']
                # 构建运行时间
                build_running_timestamp = now_timestamp - build_timestamp
                job_running_time = float(build_running_timestamp / 1000 / 60 / 60)
                job['job_running_hours'] = job_running_time
                job['job_build_date'] = build_data['build_date']
                job['job_url'] = url
                send_data.append(job)
    
    for data in send_data:
        # 如果job运行时间超过2个小时, 运行jenkins的job停止命令把对应的job构建停掉
        if data['job_running_hours'] > 2:
            print(data)

            job_url = data['job_url']
            job_number = data['number']

            replace_job_name = re.sub('(http://.*/jenkins/job/|https://.*/jenkins/job/)', '', job_url)
            replace_job_name_by_relabel = re.sub('(job/)', '', replace_job_name)
            replace_job_name_by_relabel = replace_job_name_by_relabel.lstrip('/')
            replace_job_name_by_relabel = replace_job_name_by_relabel.rstrip('/')

            res = jenkins_server.stop_job(replace_job_name_by_relabel, job_number)
            print(res)